package me.cjj.android.assignment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import io.github.kexanie.library.MathView
import kotlinx.android.synthetic.main.activity_quiz.*
import me.cjj.android.assignment.model.IQuestion
import me.cjj.android.assignment.model.LinearQuestion
import me.cjj.android.assignment.model.QuadraticQuestion
import java.util.*

class QuizActivity : AppCompatActivity() {

    private fun Intent.applyTimeCost(bar: LongArray) = putExtra("time_cost", bar)
    private fun Intent.applyCorrectResult(bar: BooleanArray) = putExtra("correct_result", bar)

    private fun Context.startResultActivity(timeCost: LongArray, correctResult: BooleanArray) =
            Intent(this, ResultActivity::class.java).apply { applyTimeCost(timeCost) }
                    .apply { applyCorrectResult(correctResult) }
                    .let(this::startActivity)

    private var currentPosition: Int = 0
    private var currentQuestion: IQuestion? = null
    private val timeCost: LongArray = kotlin.LongArray(10)
    private val correctResult: BooleanArray = kotlin.BooleanArray(10)

    private var startTime: Long = 0

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_quiz)
        btnSubmit.setOnClickListener({
            submit()
        })
        onNext(tvQuestion)
        startTime = System.currentTimeMillis()
        currentQuestion = generateLinear()
        tvQuestion.text = "${currentQuestion!!.getQuestionText()}, what is x?"
        generateAnswerLayout(llAnswer, currentQuestion!!)
    }

    @SuppressLint("SetTextI18n")
    private fun submit(): Boolean {
        val childCount = llAnswer.childCount
        val answers = FloatArray(childCount)
        for (index in 0..(childCount - 1)) {
            val editText = llAnswer.getChildAt(index) as EditText
            val answer = editText.text
            if (answer.isEmpty()) {
                Toast.makeText(llAnswer.context, "Please enter all answer", Toast.LENGTH_LONG).show()
                return false
            }
            try {
                answers[index] = answer.toString().toFloat()
            } catch (e: Exception) {
                Toast.makeText(llAnswer.context, "Please answer the float", Toast.LENGTH_LONG).show()
                return false
            }
        }
        val judgeResult = currentQuestion!!.judge(*answers)
        if (judgeResult) {
            tvResult.text = "Correct!!!"
        } else {
            val answerText = currentQuestion!!.getAnswerText()
            tvResult.text = "Wrong Answer,corrent answer is " + answerText
        }
        correctResult[currentPosition] = judgeResult
        btnSubmit.visibility = View.GONE
        return true
    }

    private fun onNext(textView: MathView) {
        findViewById<Button>(R.id.btnNext).setOnClickListener({
            if (!submit()) {
                return@setOnClickListener
            }
            timeCost[currentPosition] = System.currentTimeMillis() - startTime
            currentPosition++
            if (currentPosition == 9) {
                startResultActivity(timeCost, correctResult)
                return@setOnClickListener
            }
            startTime = System.currentTimeMillis()
            btnSubmit.visibility = View.VISIBLE
            val question: IQuestion = if (currentPosition < 5) {
                generateLinear()
            } else {
                generateQuadratic()
            }
            textView.text = "${question.getQuestionText()}, what is x?"
            currentQuestion = question
            generateAnswerLayout(llAnswer, question)
        })
    }

    private fun generateAnswerLayout(llAnswer: LinearLayout, question: IQuestion) {
        llAnswer.removeAllViews()
        val answerCount = question.getAnswerCount() - 1
        for (index in 0..answerCount) {
            LayoutInflater.from(this).inflate(R.layout.layout_answer, llAnswer, true)
        }
        val childAt = llAnswer.getChildAt(0)
        childAt.post {
            childAt.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0))
            childAt.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0))
        }
    }

    private fun generateLinear(): IQuestion {
        val k = generateParam()
        val d = generateParam()
        return LinearQuestion(k, d)
    }

    private fun generateQuadratic(): IQuestion {
        val a = generateParam()
        val b = generateParam()
        val c = generateParam()
        val quadraticQuestion = QuadraticQuestion(a, b, c)
        if (!quadraticQuestion.isValid()) {
            return generateQuadratic()
        }
        return quadraticQuestion
    }

    private fun generateParam() = Random().nextInt(199) - 99

}
